//
//  HandlePhotoViewController.m
//  TakePhotoDemo
//
//  Created by YangShuai on 16/8/31.
//  Copyright © 2016年 ys. All rights reserved.
//

#import "HandlePhotoViewController.h"
#import "ConstDefine.h"
#define styleImageNameArray @[@"A.png",@"B.png",@"C.png"]
#define styleNameArray @[@"我是书虫儿",@"此书要火",@"超级阅读达人"]
@interface HandlePhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    UIButton* _saveButton;
    UIButton* _shareButton;
    UIButton* _currentButton;
}
@property(nonatomic,strong)UIView* handleView;
@property(nonatomic,strong)UICollectionView* collectionView;
@property(nonatomic,strong)UIImageView* styleImageView;
@property(nonatomic,strong)UIImageView* photoImageView;
@property(nonatomic,strong)NSArray* photoStyleArray;
@property(nonatomic,strong)NSURLSessionTask* uploadTask;
@end

@implementation HandlePhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSMutableArray* oriStyleArr = [NSMutableArray new];
    for (int i = 0; i < 3; i ++) {
        NSDictionary* oneStyleDict =@{@"id":@(i + 1),@"isNew":@(0),@"title":styleNameArray[i],@"url":styleImageNameArray[i]};
        [oriStyleArr addObject:oneStyleDict];
    }
    self.photoStyleArray = oriStyleArr;
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F0F1F5"];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 56)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = NSLocalizedString(@"photoFinish", "");
    titleLabel.font = [UIFont boldSystemFontOfSize:22];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPad) {
        self.naviBar = [JRNaviBar getJRNaviBarWithSuperView:self.contentView centerView:titleLabel leftViews:nil rightViews:nil];
    }else{
        titleLabel.frame = CGRectMake(0, 0, 200, 25);
        titleLabel.font = [UIFont boldSystemFontOfSize:15];
        self.naviBar = [JRNaviBar getJRNaviBarWithSuperView:self.contentView centerView:titleLabel leftViews:nil rightViews:nil];
    }
    [self addBackView];
    //
    [self viewsLayout];
    [self getPhotoStyle];
}
//获取边框样式
-(void)getPhotoStyle{
    _photoStyleArray = self.sourceUrlsDict[@"data"][@"frames"];
    [_collectionView reloadData];
}

//UI布局
-(void)viewsLayout{
    //view
    self.handleView = [[UIView alloc] init];
    _handleView.backgroundColor = [UIColor clearColor];
    //self.handleView.backgroundColor = [UIColor colorWithHexString:@"#B2ABDD"];
    [self.view addSubview:_handleView];
    CGFloat ratio_fit = 1;
    CGFloat ratio_handle = 520.0 / 540;
    [_handleView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.size.JRMAS_equalTo(CGSizeMake(540, 520));
        make.top.JRMAS_equalTo(90);
        make.centerX.JRMAS_equalTo(16);
    }];
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        [_handleView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
            make.left.JRMAS_equalTo(35);
            make.top.JRMAS_equalTo(90);
            make.centerX.JRMAS_equalTo(10);
            make.height.JRMAS_equalTo(_handleView.JRMAS_width).multipliedBy(ratio_handle);
        }];
    }
    [self.view layoutIfNeeded];
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        ratio_fit = 540 / _handleView.width;
    }
    //成像区域
    UIImageView* photoImageview = [[UIImageView alloc] init];
    if (self.isCameraFront) {
        photoImageview.transform = CGAffineTransformMakeScale(-1, 1);
    }
    photoImageview.clipsToBounds = YES;
    photoImageview.contentMode = UIViewContentModeScaleAspectFill;
    photoImageview.image = self.photo;
    photoImageview.layer.borderColor = [UIColor colorWithHexString:@"#B2ABDD"].CGColor;
    photoImageview.layer.borderWidth = 4 / ratio_w;
    [_handleView addSubview:photoImageview];
    [photoImageview JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(0);
        make.right.JRMAS_equalTo(-34 / ratio_fit);
        make.top.JRMAS_equalTo(0);
        make.height.JRMAS_equalTo(photoImageview.JRMAS_width).multipliedBy(1);
    }];
    self.photoImageView = photoImageview;
    //花边区域
    UIImageView* styleImageView = [[UIImageView alloc] init];
    [_handleView addSubview:styleImageView];
    [styleImageView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(photoImageview);
    }];
    self.styleImageView = styleImageView;
    //图书封面
    UIImageView* bookCoverImageView = [[UIImageView alloc] init];
    bookCoverImageView.image = self.bookCoverImage;
    //bookCoverImageView.transform = CGAffineTransformMakeRotation(M_PI_4);
    [_handleView addSubview:bookCoverImageView];
    [bookCoverImageView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.bottom.right.JRMAS_equalTo(0);
        make.size.JRMAS_equalTo(CGSizeMake(128 / ratio_fit, 170 / ratio_fit));
    }];
    //精灵
    UIImageView* spritImageView = [[UIImageView alloc] init];
    spritImageView.image = self.spiritImage;
    [_handleView addSubview:spritImageView];
    [spritImageView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(photoImageview);
    }];
    //分享/重新拍照 View
    UIImageView* share_retakeImageView = [[UIImageView alloc] init];
    share_retakeImageView.userInteractionEnabled = YES;
    share_retakeImageView.image = [UIImage imageNamed:@"btn_bg_pink.png"];
    [self.view addSubview:share_retakeImageView];
    [share_retakeImageView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.right.bottom.JRMAS_equalTo(0);
        make.height.JRMAS_equalTo(68 / ratio_w);
    }];
    //retakeButton
    UIButton* retakeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [retakeButton setTitle:NSLocalizedString(@"redo", "") forState:UIControlStateNormal];
    [retakeButton addTouchScaleTransitions];
    retakeButton.titleLabel.font = [UIFont boldSystemFontOfSize:26 / ratio_w];
    [retakeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [retakeButton addTarget:self action:@selector(reTakePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [share_retakeImageView addSubview:retakeButton];
    [retakeButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.top.bottom.JRMAS_equalTo(0);
        make.width.JRMAS_equalTo(share_retakeImageView).multipliedBy(0.333333);
    }];
    //saveButton
    UIButton* saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveButton setTitle:NSLocalizedString(@"savePhoto", "") forState:UIControlStateNormal];
    [saveButton addTouchScaleTransitions];
    saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:26 / ratio_w];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(savePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [share_retakeImageView addSubview:saveButton];
    [saveButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(retakeButton.JRMAS_right);
        make.top.bottom.JRMAS_equalTo(0);
        make.width.JRMAS_equalTo(share_retakeImageView.JRMAS_width).multipliedBy(0.333333);
    }];
    _saveButton = saveButton;
    //shareButton
    UIButton* shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setTitle:NSLocalizedString(@"share", "") forState:UIControlStateNormal];
    [shareButton addTouchScaleTransitions];
    shareButton.titleLabel.font = [UIFont boldSystemFontOfSize:26 / ratio_w];
    [shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [share_retakeImageView addSubview:shareButton];
    [shareButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(saveButton.JRMAS_right);
        make.top.bottom.JRMAS_equalTo(0);
        make.width.JRMAS_equalTo(share_retakeImageView.JRMAS_width).multipliedBy(0.333333);
    }];
    _shareButton = shareButton;
    
    //分割线
    UIView* btnSepView_one = [[UIView alloc] init];
    btnSepView_one.backgroundColor = [UIColor whiteColor];
    [share_retakeImageView addSubview:btnSepView_one];
    [btnSepView_one JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(retakeButton.JRMAS_right);
        make.centerY.JRMAS_equalTo(0);
        make.size.JRMAS_equalTo(CGSizeMake(1, 44 / ratio_w));
    }];
    
    UIView* btnSepView_two = [[UIView alloc] init];
    btnSepView_two.backgroundColor = [UIColor whiteColor];
    [share_retakeImageView addSubview:btnSepView_two];
    [btnSepView_two JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(saveButton.JRMAS_right);
        make.centerY.JRMAS_equalTo(0);
        make.size.JRMAS_equalTo(CGSizeMake(1, 44 / ratio_w));
    }];
    
    //collectionView
    //创建一个Flowlayout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //设置layout属性的最小左右距离
    layout.minimumInteritemSpacing = 0;
    //设置上下最小间距
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake(256 / ratio_w, 296 / ratio_w);
    //设置分区上下左右边距
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //利用layout创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.right.JRMAS_equalTo(1);
        make.bottom.JRMAS_equalTo(share_retakeImageView.JRMAS_top).offset(-30);
        make.height.JRMAS_equalTo(296 / ratio_w);
    }];
    self.collectionView.backgroundColor = [UIColor colorWithHexString:@"#F0F1F5"];
    //注册cell
    [self.collectionView registerClass:[PhotoStyleCollectionViewCell class] forCellWithReuseIdentifier:_id_PhotoStyleCollectionCell];
    [self.collectionView registerNib:[UINib nibWithNibName:@"PhotoStyleCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:_id_PhotoStyleCollectionCell];
}
//重新拍照
-(void)reTakePhoto:(UIButton*)button{
    [_uploadTask cancel],_uploadTask = nil;
    [[NetGetPostsWithCache shareInstance] cancelUploadPhotoPath];
    [self.navigationController popViewControllerAnimated:YES];
}
//保存
-(void)savePhoto:(UIButton*)button{
    _currentButton = _saveButton;
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* userName = uinfo.userName;
    if (!userName || userName.length < 1) {
        userName = [NSString stringWithFormat:@"User_%@",uinfo.uCode];
    }
    _saveButton.enabled = NO;
    _shareButton.enabled = NO;
    UIImage* handleImage = [_handleView viewShot];
    YSAssetsLibrary *library = [YSAssetsLibrary defaultAssetsLibrary];
    [library saveImage:[UIImage imageWithData:UIImagePNGRepresentation(handleImage)] completion:nil];
    [self.funcPage exchangeBookImage:handleImage];
    //
    [DataProcessing do_Main:^{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    } delay:0.3];
    //
    [self uploadPhotoToUpYunWithUid:uinfo.uid BookId:_bookid ActivityId:self.activityId HurdleNo:_hurdleNo Image:handleImage Success:^(NSURLResponse *response, id responseData) {
        _saveButton.enabled = YES;
        _shareButton.enabled = YES;
    } Failure:^(NSError *error) {
        _saveButton.enabled = YES;
        _shareButton.enabled = YES;
    } Progress:nil];
}
//
-(void)tapBack{
    if (_currentButton == _shareButton) {
        [_uploadTask cancel],_uploadTask = nil;
        [[NetGetPostsWithCache shareInstance] cancelUploadPhotoPath];
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

//分享
-(void)shareAction:(UIButton*)button{
    //
    _currentButton = _shareButton;
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* userName = uinfo.userName;
    if (!userName || userName.length < 1) {
        userName = [NSString stringWithFormat:@"User_%@",uinfo.uCode];
    }
    _shareButton.enabled = NO;
    _saveButton.enabled = NO;
    UIImage* handleImage = [_handleView viewShot];
    [[WaitingShow shareSingleShow] showWaitingString:NSLocalizedString(@"Uploading", "") inSuperView:self.view];
    [self uploadPhotoToUpYunWithUid:uinfo.uid BookId:_bookid ActivityId:_activityId HurdleNo:_hurdleNo Image:handleImage Success:^(NSURLResponse *response, id responseData) {
        _shareButton.enabled = YES;
        _saveButton.enabled = YES;
        [[WaitingShow shareSingleShow] hideShow];
        NSString* shareUrl = JRPhotoShare_URL(@(uinfo.uid), @(self.bookid), @(self.activityId));
        if (_hurdleNo == 0) {
            [[ShareManager shareManager] JRShareWithText:[NSString stringWithFormat:NSLocalizedString(@"photoShareText", nil),userName,_bookName] ImageArray:@[handleImage] Url:[NSURL URLWithString:shareUrl] Title:[NSString stringWithFormat:NSLocalizedString(@"photoShareTitle", nil),userName] Type:SSDKContentTypeAuto BaseView:button statusChange:nil];
        }else{
            [[ShareManager shareManager] JRSharePhotoContainExplorWithText:[NSString stringWithFormat:NSLocalizedString(@"photoShareText", nil),userName,_bookName] ImageArray:@[handleImage] Url:[NSURL URLWithString:shareUrl] Title:[NSString stringWithFormat:NSLocalizedString(@"photoShareTitle", nil),userName] Type:SSDKContentTypeAuto BaseView:button BookId:_bookid ActivityId:_activityId HurdleNo:_hurdleNo Success:^(NSDictionary *retDict) {
                YSAssetsLibrary *library = [YSAssetsLibrary defaultAssetsLibrary];
                [library saveImage:[UIImage imageWithData:UIImagePNGRepresentation(handleImage)] completion:nil];
                [self showShareSuccessAlterView];
            } failure:^(NSError *error) {
                [self showShareFailAlertView];
            } statusChange:^(SSDKResponseState state, SSDKPlatformType type) {
                if (state == SSDKResponseStateBegin) {
                    [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_TakePhotoShareSuccess Param:@(self.bookid).description];
                }
            }];
        }
    } Failure:^(NSError *error) {
        button.enabled = YES;
        [[WaitingShow shareSingleShow] hideShow];
        if (![WaitingShow shareSingleShow].isShowing && error.code != -999) {
            [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"netfailed", "") andAutoHide:YES];
        }
    } Progress:nil];
}
//上传照片到UpYun
-(void)uploadPhotoToUpYunWithUid:(NSInteger)uid BookId:(NSInteger)bookId ActivityId:(NSInteger)activityId HurdleNo:(NSInteger)hurdleNo Image:(UIImage*)photoImage Success:(void (^)(NSURLResponse *response, id responseData))success Failure:(void (^)(NSError *error))failure Progress:(void (^)(CGFloat percent, int64_t requestDidSendBytes))progress {
    NSDate* date = [NSDate date];
    long long time = [DataProcessing timestampFromNSDate:date];
    NSString* keyPath = [NSString stringWithFormat:@"/ugc/picture/%@/%@/%@.png",@(uid),@(bookId),@(time)];
    UpYun *uy = [[UpYun alloc] init];
    uy.sessionBlocker = ^(NSURLSessionTask* task){
        _uploadTask = task;
    };
    uy.successBlocker = ^(NSURLResponse *response, id responseData)
    {
        NSDictionary* paramDict = @{@"url":keyPath,@"hurdleNo":@(hurdleNo),@"bookId":@(_bookid)};
        [[NetGetPostsWithCache shareInstance] storePathForPhotoInUpYunWithActivityId:activityId PathArray:@[paramDict] Success:^(NSDictionary *retDict) {
            if (success) success(response,responseData);
        } Failure:^(NSError *error) {
            
        }];
    };
    uy.failBlocker = ^(NSError *error)
    {
        if (failure) failure(error);
    };
    uy.progressBlocker = ^(CGFloat percent, int64_t requestDidSendBytes)
    {
        if (progress) progress(percent,requestDidSendBytes);
    };
    [uy uploadFile:photoImage saveKey:keyPath];
}


#pragma mark -
#pragma mark - collectionViewDelegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photoStyleArray.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoStyleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_id_PhotoStyleCollectionCell forIndexPath:indexPath];
    NSDictionary* oneStyleDcit = _photoStyleArray[indexPath.row];
    if (indexPath.row < 3) {
        [cell.styleImageView JRSD_setImageWithURL:[NSURL URLWithString:oneStyleDcit[@"url"]] placeholderImage:[UIImage imageNamed:styleImageNameArray[indexPath.item]] options:JRSDWebImageRefreshCached];
        cell.styleNameLabel.text = oneStyleDcit[@"title"];
    }else{
        [cell.styleImageView JRSD_setImageWithURL:[NSURL URLWithString:oneStyleDcit[@"url"]] placeholderImage:nil options:JRSDWebImageRefreshCached];
        cell.styleNameLabel.text = oneStyleDcit[@"title"];
    }
    
    return  cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoStyleCollectionViewCell* cell = (PhotoStyleCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    _photoImageView.layer.borderWidth = 0;
    _styleImageView.image = cell.styleImageView.image;
}

-(void)showShareSuccessAlterView{
    [DataProcessing do_Main:^{
        //刷新Html页面
        [[WebViewController currentWebVCInstance] hurdleShareSuccessReflshWebView];
        //
        [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"shareMyDiySuccess") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self.navigationController dismissViewControllerAnimated:NO completion:^{
                    [[ReadBookVOrH_VC currentReadInstance] tapBack];
                }];
            }
        } buttonTitles:ReadLocalizedString(@"xianbuqu"),ReadLocalizedString(@"qukankan"),nil];
    } delay:0.3];
}

-(void)showShareFailAlertView{
    [DataProcessing do_Main:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ReadLocalizedString(@"talkSharefail")
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:ReadLocalizedString(@"sure")
                                              otherButtonTitles:nil, nil];
        [alert show];
    } delay:0.3];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
